package edu.umd.mhealth.lab8;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;

import edu.umd.mhealth.lab6.R;
import android.os.AsyncTask;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;



/* An HttpGetTask takes a request and an OAuthService, sends a GET request to passed service, and then creates a new TextView based
 * on returned data. */
public class HttpGetTask extends AsyncTask<String, Void, Response>{
	private ViewGroup mContainer; 
	private OAuthService service;
	private Token accessToken;

	public HttpGetTask(ViewGroup container, OAuthService service, Token accessToken){
		this.mContainer = container;
		this.service = service;
		this.accessToken = accessToken;
	}

	@Override
	protected Response doInBackground(String... params) {
		OAuthRequest request = new OAuthRequest(Verb.GET, params[0]);
		service.signRequest(accessToken, request);
		Response response = request.send();
		return response;
	}

	protected void onPostExecute(Response response){
		if (response.getCode() != 200){
			Toast.makeText(mContainer.getContext(), "server error", 30).show();
		} else {
			Toast.makeText(mContainer.getContext(), response.getBody(), 200).show();
	
			JSONObject json;
			
			try {
				// parse response for new data
				json = new JSONObject(response.getBody());
				JSONArray arr = json.getJSONArray("weight");
				JSONObject weightObject = arr.getJSONObject(0);
				double weight = weightObject.getDouble("weight") * 2.2;
				String weightString = Double.toString(weight);
				Toast.makeText(mContainer.getContext(), weightString, 200).show();

				
				// get current view
				TextView tv = (TextView) mContainer.findViewById(R.id.tv);
				tv.setText(weightString);

			} catch (JSONException e) {
				e.printStackTrace();
			}

		}
	}
}




